package ex02.pyrmont;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author: 顶风少年
 * @Description:
 * @date: 2023/4/29
 **/
public class HttpServer {
    //停止指令
    private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";
    //停止标记
    private boolean shutdown = false;

    public static void main(String[] args) {
        HttpServer server = new HttpServer();
        server.await();
    }

    public void await() {
        ServerSocket serverSocket = null;
        int port = 8080;
        try {
            //请求进入连接队列的最大长度,服务端的 accept()方法会取出连接,该变量不设置默认为50
            serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
        while (!shutdown) {
            Socket socket = null;
            InputStream input = null;
            OutputStream output = null;
            try {
                //接入客户端
                socket = serverSocket.accept();
                input = socket.getInputStream();
                output = socket.getOutputStream();

                //创建request解析入参
                Request request = new Request(input);
                request.parse();
                //通过入参判断是否是停止操作
                String uri = request.getUri();
                shutdown = uri.equals(SHUTDOWN_COMMAND);
                if (!shutdown) {
                    Response response = new Response(output);
                    response.setRequest(request);
                    //用于处理servlet请求
                    if (uri.startsWith("/servlet")) {
                        ServletProcessor processor = new ServletProcessor();
                        processor.process(request,response);
                    }else{
                        //用于处理静态请求
                        StaticResourceProcessor processor = new StaticResourceProcessor();
                        processor.process(request,response);
                    }
                }
                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }
    }
}
